//
//  PreferencesDelegate.m
//
//  Created by Alexander Chaika on 23.01.12.
//  Copyright 2012 by Alexander Chaika. All rights reserved.
//

#import "resource.h"

#import "PreferencesDelegate.h"
#import "ValueTransformer.h"

@implementation PreferencesDelegate

- (id)init {
    self = [super init];
    if (self) {
		// registering some transformers for binding
		[NSValueTransformer setValueTransformer:[[[StartSyncTransformerForLabel alloc] init] autorelease]
										forName:@"StartSyncTransformerForLabel"];
		[NSValueTransformer setValueTransformer:[[[StartSyncTransformerForButton alloc] init] autorelease]
										forName:@"StartSyncTransformerForButton"];
		[NSValueTransformer setValueTransformer:[[[LastSyncDateTransformer alloc] init] autorelease]
										forName:@"LastSyncDateTransformer"];
		[NSValueTransformer setValueTransformer:[[[ScheduledSyncDateTransformer alloc] init] autorelease]
										forName:@"ScheduledSyncDateTransformer"];
    }
    return self;
}

- (IBAction)accountSetup:(id)sender {
	// stop all synchronization
	[sync stop];
	
	// Creating URI using client id, redirect uri
	NSString *uri = [NSString stringWithFormat:@"https://accounts.google.com/o/oauth2/auth?scope=%@&redirect_uri=%@&response_type=code&client_id=%@",
					 google_api_scope, redirect_uri, client_id];
	
	// Starting default browser with specific URL
	[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:uri]];
	
	// Show modal dialog to get created identifier
	[NSApp beginSheet:accountSheet
	   modalForWindow:prefWindow
		modalDelegate:self
	   didEndSelector:@selector(accountDidEnd: returnCode: contextInfo:)
		  contextInfo:nil];
}

- (void)accountDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
	// clear access token
	sync.accessToken = nil;
	
	// start all synchronization
	[sync start];
}

- (IBAction)changeStartSync:(id)sender {
	BOOL startSync = ![[NSUserDefaults standardUserDefaults] boolForKey:kSyncStarted];
	[[NSUserDefaults standardUserDefaults] setBool:startSync forKey:kSyncStarted];
	
	// restart synchronization here to stop pending opertions
	[sync restart];
}

@end
